package com.yao.component.pictureselector;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

//import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
//import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
//import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
//import com.nostra13.universalimageloader.core.DisplayImageOptions;
//import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
//import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
//import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
//import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
//import com.nostra13.universalimageloader.utils.StorageUtils;
import com.yao.component.pictureselector.adapter.VideoGrideAdapter;
import com.yao.component.pictureselector.bean.VideoModel;

import java.util.ArrayList;


public class VideoBrowseActivity extends BaseActivity implements OnClickListener
{

	public  static  int maxSelectCount=9;
	public static ArrayList<String> mSelectedVideo = new ArrayList<>();
	private AlertDialog mProgressDialog;
	private LinearLayout finish;

	private ArrayList<VideoModel> videoList=new ArrayList<>();
	private GridView mGirdView;
	private VideoGrideAdapter mAdapter;


	private TextView preview,finish_tv;
	private TextView select_count;
	int totalCount = 0;
	private UpDataReciver reciver;
	private int mScreenHeight;
	private boolean isSingle;


	private Handler mHandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			mProgressDialog.dismiss();
			// 为View绑定数据
			data2View();

		}
	};

	/**
	 * 为View绑定数据
	 */
	private void data2View()
	{
		if (totalCount == 0)
		{
			Toast.makeText(getApplicationContext(), "未查找到视频",
					Toast.LENGTH_SHORT).show();
			return;
		}

		mAdapter = new VideoGrideAdapter(VideoBrowseActivity.this, videoList,
				R.layout.video_grid_item,isSingle);
		mAdapter.setOnPictureClickListener(new VideoGrideAdapter.onVideoClickListener() {
			@Override
			public void onAddPicture(String path) {
				if (!mSelectedVideo.contains(path)){
					mSelectedVideo.add(path);
					showSelectCount();
				}

			}

			@Override
			public void onRemovePicture(String path) {
				if (mSelectedVideo.contains(path)){
					mSelectedVideo.remove(path);
					showSelectCount();
				}
			}
		});
		mGirdView.setAdapter(mAdapter);


	};



	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_video_browse);
		showTitle("视频");
		showRightTv("取消", new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSelectedVideo.clear();
				returnResult();

			}
		});

		int maxCount=getIntent().getIntExtra("MAX_COUNT",-1);
		isSingle=getIntent().getBooleanExtra("IS_SINGLE",false);
		if (maxCount!=-1){
			maxSelectCount=maxCount;
		}else {
			maxSelectCount=9;
		}

		initView();
		getVideos();

		IntentFilter filter=new IntentFilter();
		filter.addAction("com.yao.component.pictureselector.selectupdata");
		reciver=new UpDataReciver();
		registerReceiver(reciver,filter);
//		initEvent();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(reciver);
	}

	@Override
	protected void onResume() {
		super.onResume();
		showSelectCount();
//		if (mAdapter!=null){
//			mAdapter.notifyDataSetChanged();
//		}
	}
	public void showSelectCount(){
		if (mSelectedVideo.size()>0){
			select_count.setVisibility(View.VISIBLE);
			select_count.setText(mSelectedVideo.size()+"");
			preview.setTextColor(getResources().getColor(R.color.black));
			finish_tv.setTextColor(getResources().getColor(R.color.bg_red));
		}else {
			select_count.setVisibility(View.GONE);
			preview.setTextColor(getResources().getColor(R.color.text_hint_gray));
			finish_tv.setTextColor(getResources().getColor(R.color.bg_red_tran));
		}
	}




	private void getVideos()
	{
//		if (!Environment.getExternalStorageState().equals(
//				Environment.MEDIA_MOUNTED))
//		{
//			Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
//			mSelectedVideo.clear();
//			returnResult();
//			return;
//		}
		mProgressDialog=new AlertDialog.Builder(this).create();

		mProgressDialog.show();
		mProgressDialog.setContentView(LayoutInflater.from(this).inflate(R.layout.progress_dialog,null));

		new Thread(new Runnable()
		{
			@Override
			public void run()
			{

				String firstImage = null;

				Uri mImageUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = VideoBrowseActivity.this
						.getContentResolver();

				Cursor mCursor = mContentResolver.query(mImageUri, null,
						MediaStore.Video.Media.MIME_TYPE + "=?",
						new String[] { "video/mp4"},
						MediaStore.Video.Media.DATE_MODIFIED);
				VideoModel video;
				Log.e("TAG", mCursor.getCount() + "");
				while (mCursor.moveToNext())
				{
					video=new VideoModel();
					// 获取图片的路径
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Video.Media.DATA));
					long size = mCursor.getLong(mCursor
							.getColumnIndex(MediaStore.Video.Media.SIZE));
					String title = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Video.Media.TITLE));
					long duration = mCursor.getLong(mCursor
							.getColumnIndex(MediaStore.Video.Media.DURATION));
					video.setPath(path);
					video.setDuration(duration);
					video.setSize(size);
					video.setTitle(title);
					videoList.add(video);
				}

				mCursor.close();
				totalCount=videoList.size();
				mHandler.sendEmptyMessage(0x110);

			}
		}).start();

	}

	/**
	 * 初始化View
	 */
	private void initView()
	{
		finish=(LinearLayout)findViewById(R.id.finish);
		finish.setOnClickListener(this);
		mGirdView = (GridView) findViewById(R.id.id_gridView);
		preview = (TextView) findViewById(R.id.preview);
		preview.setOnClickListener(this);
		select_count = (TextView) findViewById(R.id.select_count);
		finish_tv=(TextView) findViewById(R.id.finish_tv);
//		mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);
		if (isSingle){
			findViewById(R.id.id_bottom_ly).setVisibility(View.GONE);
		}else {
			findViewById(R.id.id_bottom_ly).setVisibility(View.VISIBLE);
			findViewById(R.id.preview).setVisibility(View.GONE);
		}
		mGirdView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (!isSingle){
					previewVideo(videoList.get(position).getPath());
				}else {
					mSelectedVideo.add(videoList.get(position).getPath());
					returnResult();
				}


			}
		});
	}
	public void previewVideo(String path){
		if (path.endsWith(".mp4")){
			Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
			Uri data = Uri.parse(path);
			intent.setDataAndType(data, "video/mp4");
			startActivity(intent);
		}

	}
//	private void initEvent()
//	{
//		/**
//		 * 为底部的布局设置点击事件，弹出popupWindow
//		 */
//		mBottomLy.setOnClickListener(new OnClickListener()
//		{
//			@Override
//			public void onClick(View v)
//			{
//				mListImageDirPopupWindow
//						.setAnimationStyle(R.style.anim_popup_dir);
//				mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0,0);
//				// 设置背景颜色变暗
//				WindowManager.LayoutParams lp = getWindow().getAttributes();
//				lp.alpha = .3f;
//				getWindow().setAttributes(lp);
//			}
//		});
//	}




	@Override
	public void onClick(View v) {
		int id=v.getId();
		if (id==R.id.finish){
			if (mSelectedVideo.size()>0){
				returnResult();
			}
		}
//		switch (v.getId()){
//			int id=v.getId();
//			case  R.id.finish:
//				if (mSelectedVideo.size()>0){
//					returnResult();
//				}
//				break;
//			case R.id.preview:
//				if (mSelectedVideo.size()>0){
//					Intent intent=new Intent(PhotoBrowseActivity.this,PhotoPreviewActivity.class);
//					intent.putStringArrayListExtra("paths",mSelectedVideo);
//					intent.putExtra("position",0);
//					startActivityForResult(intent,2);
//				}
//				break;
//		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		mSelectedVideo.clear();
		returnResult();
	}
	public void returnResult(){
		Intent intent = new Intent();
		intent.setAction("com.yao.component.pictureselector.selectimage");
		intent.putStringArrayListExtra("select_image", mSelectedVideo);
		VideoBrowseActivity.this.sendBroadcast(intent);
		VideoBrowseActivity.this.finish();
	}
	class UpDataReciver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			if (mAdapter!=null){
				mAdapter.notifyDataSetChanged();
			}
		}
	}
}
